package com.han.walkman.controller;

import com.han.walkman.entity.LoginBackEntity;
import com.han.walkman.entity.UserEntity;
import com.han.walkman.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.json.JSONException;
import org.json.JSONObject;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.List;
import java.util.Objects;

/**
 * @Author: Hanjiafeng
 * @Date: 2020/6/12
 * @Desc:
 */
@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {

    private final UserService userService;

    public UserController(UserService userService) {
        this.userService = userService;
    }

    @PostMapping(value = "login")
    public LoginBackEntity login(String code, String nickname) {
        LoginBackEntity loginBackEntity = new LoginBackEntity();

        log.info("请求微信查询appid接口");
        //使用code请求openid和session_key
        RestTemplate restTemplate = new RestTemplate();
        String uri = "https://api.weixin.qq.com/sns/jscode2session?"
                + String.format("appid=%s", "wx0d4aaffdc61db473")
                + String.format("&secret=%s", "9dbbd9e5dc68ca5c7369dc9f043b4124")
                + String.format("&js_code=%s", code)
                + "&grant_type=authorization_code";
        String back = restTemplate.getForObject(uri, String.class);

        //解析json字符串
        JSONObject jsonObject;
        String openId;
        String sessionKey;
        try {
            jsonObject = new JSONObject(back);
            openId = jsonObject.getString("openid");
            sessionKey = jsonObject.getString("session_key");
            if (openId.isBlank() || sessionKey.isBlank()) {
                throw new JSONException("");
            }
            log.info("接口请求成功,解析到name:" + nickname + ",openid:" + openId + ",sessionKey:" + sessionKey);
        } catch (JSONException e) {
            loginBackEntity.setCode(-1);
            loginBackEntity.setMsg("未解析到关键数据");
            log.error("未解析到openid和sessionKey,uri:" + uri + "返回:" + back);
            return loginBackEntity;
        }

        //查询用户数据
        UserEntity userEntity = new UserEntity();
        userEntity.setOpenId(openId);
        userEntity.setNickname(nickname);
        List<UserEntity> entityList = userService.findAllByEntity(userEntity);
        //如果未查找到数据，或者未绑定手机号
        if (entityList.isEmpty()) {
            loginBackEntity.setCode(1);
            loginBackEntity.setMsg("未绑定手机号");
            //将临时账号写入数据库
            userEntity.setSessionKey(sessionKey);
            userEntity.setRole("2");
            userService.add(userEntity);
            return loginBackEntity;
        } else if (entityList.size() > 1) {
            loginBackEntity.setCode(2);
            loginBackEntity.setMsg("用户信息重复");
            return loginBackEntity;
        }
        userEntity = entityList.get(0);
        String phoneNumber = userEntity.getPhoneNumber();
        if (Objects.isNull(phoneNumber) || phoneNumber.isBlank()) {
            loginBackEntity.setCode(1);
            loginBackEntity.setMsg("未绑定手机号");
            //将临时账号写入数据库
            userEntity.setSessionKey(sessionKey);
            userEntity.setRole("2");
            userService.add(userEntity);
            return loginBackEntity;
        }
        loginBackEntity.setCode(0);
        loginBackEntity.setMsg("查询成功");
        loginBackEntity.setUserId(userEntity.getId());
        //将临时账号写入数据库
        userEntity.setSessionKey(sessionKey);
        userService.add(userEntity);
        return loginBackEntity;
    }

    @RequestMapping("bindPhoneNumber")
    public LoginBackEntity bindPhoneNumber(String encryptedData, String iv, int id, String name) {
        LoginBackEntity loginBackEntity = new LoginBackEntity();

        UserEntity userEntity = new UserEntity();
        userEntity.setId(id);
        userEntity = userService.findAllByEntity(userEntity).get(0);

        RestTemplate restTemplate = new RestTemplate();
        String uri = "https://mp.weixin.qq.com/debug/wxadoc/dev/api/signature.html?"
                + String.format("encryptedData=%s", encryptedData)
                + String.format("&iv=%s", iv)
                + String.format("&sessionKey=%s", userEntity.getSessionKey())
                + "&uid=";
        String back = restTemplate.getForObject(uri, String.class);

        //解析手机号
        JSONObject jsonObject;
        String phoneNumber;
        try {
            jsonObject = new JSONObject(back);
            phoneNumber = jsonObject.getString("phoneNumber");
            log.info("手机号：" + phoneNumber);
        } catch (JSONException e) {
            loginBackEntity.setCode(-1);
            loginBackEntity.setMsg(("未解析到手机号码"));
            return loginBackEntity;
        }

        userEntity.setPhoneNumber(phoneNumber);
        userEntity.setUsername(name);

        loginBackEntity.setCode(0);
        loginBackEntity.setMsg("绑定手机号成功");
        return loginBackEntity;
    }
}
